﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AppUpdates.Core
{
    public class RunApp
    {
        public static bool Run(string appPath, bool isAdmin = false)
        {
            Process process = new Process();//创建process对象
            process.StartInfo.UseShellExecute = false; //必要参数
            process.StartInfo.RedirectStandardOutput = true;//输出参数设定
            process.StartInfo.RedirectStandardInput = true;//传入参数设定
            process.StartInfo.CreateNoWindow = true;

            FileInfo fileInfo = new FileInfo(appPath);
            if (!fileInfo.Exists)
            {
                throw new FileNotFoundException(appPath);
            }

            //设置工作目录为当前工作目录
            System.IO.Directory.SetCurrentDirectory(fileInfo.DirectoryName);

            //设置要打开的程序名
            process.StartInfo.FileName = fileInfo.Name;

            if (isAdmin == false)
            {
                process.Start(); //程序启动
                //process.WaitForExit();//等待程序执行完退出进程
                process.Close(); //关闭程序
                return true;
            }


            //以管理员身份允许程序
            //获得当前登录的Windows用户标示
            System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
            System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
            //判断当前登录用户是否为管理员
            if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
            {
                //如果是管理员，则直接运行
                process.Start(); //程序启动
            }
            else
            {
                //创建启动对象
                System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                startInfo.UseShellExecute = true;
                startInfo.WorkingDirectory = Environment.CurrentDirectory;
                startInfo.FileName = "ndp48-x86-x64-allos-enu.exe";
                //设置启动动作,确保以管理员身份运行
                startInfo.Verb = "runas";
                try
                {
                    System.Diagnostics.Process.Start(startInfo);
                }
                catch
                {

                    throw;
                }
                finally
                {
                    //process.Close(); //关闭程序
                }
                //退出
            }

            System.IO.Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
            process.Close(); //关闭程序
            return true;
        }

    }
}
